package com.las.bot.cmd.other;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.StrKit;
import com.las.annotation.BotCmd;
import com.las.bot.dao.SovitsDao;
import com.las.cmd.BaseNonCommand;
import com.las.config.AppConfigs;
import com.las.nogu.commond.Constant;
import com.las.utils.HttpUtils;
import com.las.utils.JsonUtils;
import com.las.utils.mirai.CmdUtil;
import com.las.utils.mirai.MiRaiUtil;
import com.model.SovitsSetting;
import com.utils.RedisUtils;
import com.utils.ThreadUtil;
import com.utils.youdao.RecordUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;

@BotCmd(funName = "AI聊天", isMatch = false)
public class MyAiCmd extends BaseNonCommand {

    private static Logger logger = Logger.getLogger(MyAiCmd.class);

    private ThreadPoolExecutor executor = ThreadUtil.getPool();

    @Autowired
    private SovitsDao sovitsDao;

    @Override
    public void execute(JSONObject obj, Long userId, Long id, Integer type, String command, ArrayList<String> args) throws Exception {
        logger.info("开始检查AT机器人聊天功能...");
        JSONArray msgChain = obj.getJSONArray("messageChain");
        if (CollectionUtil.isNotEmpty(msgChain)) {
            Long msgId = null;
            for (int i = 0; i < msgChain.size(); i++) {
                JSONObject jsonObject = msgChain.getJSONObject(i);
                String msgType = jsonObject.getString("type");
                if ("Source".equals(msgType)) {
                    msgId = jsonObject.getLong("id");
                    break;
                }
            }
            logger.info("AI聊天功能>消息ID..." + msgId);
            if (null != msgId && msgId > 0) {
                for (int j = 0; j < msgChain.size(); j++) {
                    JSONObject jsonObject = msgChain.getJSONObject(j);
                    String msgType = jsonObject.getString("type");
                    String target = jsonObject.getString("target");
                    if ("At".equals(msgType) && AppConfigs.botQQ.equals(target)) {
                        sendChatInfo(command, userId, id, type);
                        break;
                    }
                }
            }
        }

    }

    private void sendChatInfo(String command, Long userId, Long id, Integer type) {
        logger.info("机器人聊天接受信息：" + command);
        SovitsSetting setting = sovitsDao.findByName("gpt");
        String sId = "ff83c11b-4e9b-43ea-870d-39578999c742";
        if (ObjectUtil.isNotNull(setting)) {
            String key = setting.getCodeValue();
            Object obj = RedisUtils.get(Constant.GPT_SESSION);
            if (obj != null) {
                sId = obj.toString();
            }
            if (StrUtil.isNotBlank(sId)) {
                String finalSId = sId;
                executor.execute(() -> {
                    Map<String, String> params = new HashMap<>();
                    params.put("msg", command);
                    params.put("pId", "#");
                    params.put("uId", String.valueOf(userId));
                    params.put("key", key);
                    params.put("sId", finalSId);
                    String result = HttpKit.post("http://vits.natapp1.cc/dwchat/gpt", params, null);
                    if (StrKit.notBlank(result)) {
                        logger.info("gpt响应结果：" + result);
                        JSONObject obj2 = JSONObject.parseObject(result);
                        if (obj2.getIntValue("code") == 200) {
                            String msg = obj2.getString("data");
                            msg = msg.replaceAll("#这是一个字符开头的回答。", "");
                            msg = msg.replaceAll("</is_important>", "");
                            msg = msg.replaceAll("以字符作为回答的开头", "秋蒂说");
                            if (msg.trim().startsWith("#")) {
                                msg = msg.replaceAll("#", "秋蒂说:");
                            }
                            CmdUtil.sendMessage(msg, userId, id, type);
                        }
                    }
                });
            }
        }

    }


}
